package com.match.teammates.config;

/**
 * @author 小虹
 * @version 1.0
 */
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.match.teammates.model.domain.User;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class RedisPageDataRetriever {

    private final HashOperations<String, String, Object> HashObjectValueOperations;
    private final ObjectMapper objectMapper;

    public RedisPageDataRetriever(HashOperations<String, String, Object> HashObjectValueOperations, ObjectMapper objectMapper) {
        this.HashObjectValueOperations = HashObjectValueOperations;
        this.objectMapper = objectMapper;
    }

    public Page<User> getPageFromRedis(String redisKey, Class<User> userClass) {
        Object retrievedObject = HashObjectValueOperations.get(redisKey, "userPage");
        if (retrievedObject instanceof Map) {
            try {
                // 将取出的Map对象（对应之前存储的Page序列化后的数据结构）转换为JSON字符串
                String json = objectMapper.writeValueAsString(retrievedObject);
                // 再将JSON字符串反序列化为Page对象
                return objectMapper.readValue(json, objectMapper.getTypeFactory().constructParametricType(Page.class, userClass));
            } catch (Exception e) {
                // 处理转换过程中出现的异常，比如记录日志等
                e.printStackTrace();
            }
        }
        return null;
    }
}